package com.leetcode.easy;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Classname SolutionPlusOne
 * @Description 数组尾部加一
 * @Date 2020/8/20 10:24
 * @Created by zfl
 */
public class SolutionPlusOne {
    /*
    *@Description 遍历
    *@param [digits]
    *@return int[]
    * 执行用时：0 ms, 在所有 Java 提交中击败了100.00%的用户
    * 内存消耗：38.2 MB, 在所有 Java 提交中击败了42.87%的用户
    */
    public int[] plusOne(int[] digits) {
        int len = digits.length;
        int[] nums = new int[len + 1];
        int carry = 0;
        if(digits[len - 1] + 1 > 9) {
            carry = 1;
            nums[len] = 0;
        }else {
            carry = 0;
            nums[len] = digits[len - 1] + 1;
        }
        for (int i = len - 2; i >= 0; i--) {
            if(digits[i] + carry > 9) {
                nums[i + 1] = 0;
                carry = 1;
            }else {
                nums[i + 1] = digits[i] + carry;
                carry = 0;
            }
        }
        nums[0] = carry;
        for (int num : nums) {
            System.out.print(num);
        }
        System.out.println("-------");
        if(nums[0] == 0) {
            int[] newNum = new int[len];
            for (int i = 1; i <= len; i++) {
                newNum[i - 1] = nums[i];
            }
            return newNum;
        }else {
            return nums;
        }
    }

    public int[] plusTwo(int[] digits) {
        int carry = 1;
        Deque<Integer> stack = new LinkedList<>();
        //i >= 0 || carry != 0处理最高位的边界问题
        for (int i = digits.length - 1; i >= 0 || carry != 0; i--) {
            int sum = carry;
            if(i >= 0) {
                sum += digits[i];
            }
            stack.push(sum % 10);
            carry = sum / 10;
        }
        int[] res = new int[stack.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = stack.pop();
        }
        return res;
    }
}
